package com.elitel.frame.business.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.elitel.frame.base.service.BaseRepdatasourceService;
import com.elitel.frame.base.service.BaseRepparmeterService;
import com.elitel.frame.base.service.BaseReptempletService;
import com.elitel.frame.base.service.CfgExtreportService;
import com.elitel.frame.business.service.TableFieldCommService;
import com.elitel.frame.core.util.JasperHelper;
import com.elitel.frame.main.entity.BaseRepdatasource;
import com.elitel.frame.main.entity.BaseRepparmeter;
import com.elitel.frame.main.entity.BaseReptemplate;
import com.elitel.frame.main.entity.CfgExtreport;
import com.elitel.frame.main.entity.vo.JsonDataResult;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.google.gson.JsonObject;
import com.elitel.frame.core.util.BeanFactory;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

/**
 * 
 * <pre>@ProjectName：frame-business-web    
 * @ClassName：ReportServerController    
 * @Description: TODO(报表服务接口)    
 * @author：FanWenquan  
 * @date：2018年2月9日 下午2:28:11       
 * @version </pre>
 */
@Controller
@RequestMapping("/business/reportServer")
public class ReportServerController {
	
	private static final Logger logger = LoggerFactory.getLogger(ReportServerController.class);
	
	@Autowired
	private CfgExtreportService cfgExtreportService;
	@Autowired
	private BaseRepdatasourceService baseRepdatasourceService;
	@Autowired
	private BaseRepparmeterService baseRepparmeterService;
	@Autowired
	private BaseReptempletService baseReptempletService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private SingleTableServerController singleTableServerController;
	@Autowired
	private ExtMasterController extMasterController;
	@Autowired
	private TreeConfigFiledController treeConfigFiledController;
	@Autowired
	private MultipleTableServerController multipleTableServerController;
	@Autowired
	private TableFieldCommService tableFieldCommService;
	
	/**
	 * <pre>showReportView(报表服务)   
	 * @author：FanWenquan    
	 * @date：2018年2月9日 下午2:28:39   
	 * @param pageNO
	 * @param conQuery
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/reportView")
	public void showReportView(String serviceID, String pageNO, String conQuery, HttpServletResponse response) throws Exception {
			// 报表数据源
			JRDataSource dataSourceMain = null;
			//条件的集合
			Map<String, Object> pays = null;
			if(null != conQuery && !conQuery.equals("")) {
				pays =(Map)JSON.parse(conQuery);
			}
			//{"@param_DB_NAME":"ChinaGWDatabase","@param_DT_NAME_CN":"配置县名"}
			try {
			Map<String, Object> exporterParameters = new HashMap<String, Object>();
			
			CfgExtreport reportConfigByGuid = cfgExtreportService.getReportConfigByGuid(serviceID);
			List<BaseRepdatasource> dslist = baseRepdatasourceService.getReportDataSourceByServer(serviceID);
			for (BaseRepdatasource ds : dslist) {
				if(null != ds.getDataserviceid() && null != ds.getServicetype()) {
					if(ds.getRepdatasource().equals("DefaultDataSource")) {
						List<BaseRepparmeter> dspalist = baseRepparmeterService.getReportParmByDataServer(serviceID, ds.getDataserviceid(), ds.getRepdatasource());
						String serverQuery = returnQuery(pays, dspalist);
						List dafaultdata = (List)getDataRows(ds.getServicetype(), ds.getDataserviceid(),serverQuery);
					    dataSourceMain = new JRBeanCollectionDataSource(dafaultdata);
					}else {
						List<BaseRepparmeter> sonlist = baseRepparmeterService.getReportParmByDataServer(serviceID, ds.getDataserviceid(), ds.getRepdatasource());
						String serverQuery = returnQuery(pays, sonlist);
						List datarows = (List)getDataRows(ds.getServicetype(), ds.getDataserviceid(),serverQuery);
						JRDataSource otherdata = new JRBeanCollectionDataSource(datarows);
						exporterParameters.put(ds.getRepdatasource(), otherdata);
					}
				}
			}
			List<BaseRepparmeter> parmlist = baseRepparmeterService.getReportParmByServerByType(serviceID, "templateparmeter");
			for (BaseRepparmeter parm : parmlist) {
				if((null != parm.getOptionvalue() || !"".equals(parm.getOptionvalue()))) {
					exporterParameters.put(parm.getParmetername(), parm.getOptionvalue());
				}
				for (String str : pays.keySet()) {
					if(null != parm.getAliasname() && str.equals(parm.getAliasname())) {
						exporterParameters.put(parm.getParmetername(), pays.get(str));
					}else if(null == parm.getAliasname() && str.equals(parm.getParmetername())) {
						exporterParameters.put(parm.getParmetername(), pays.get(str));
					}
				}
			}
			
			BaseReptemplate template = baseReptempletService.getReptemplateByServiceid(serviceID);
			String realpath = template.getTemplateUrl();//request.getSession().getServletContext().getRealPath(template.getTemplateUrl());
			
			if(null != reportConfigByGuid.getShowtype() && "html".equals(reportConfigByGuid.getShowtype())) {
				JasperHelper.showHtml(UUID.randomUUID().toString() , realpath, request,
						response, exporterParameters, dataSourceMain);
			}else if(null != reportConfigByGuid.getShowtype() && "pdf".equals(reportConfigByGuid.getShowtype())) {
				JasperHelper.showPdf(UUID.randomUUID().toString() , realpath, request,
						response, exporterParameters, dataSourceMain);
			}
			
			} catch (JRException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	/**
	 * <pre>showReportView(报表服务导出功能)   
	 * @author：FanWenquan    
	 * @date：2018年2月27日 下午5:24:47   
	 * @param serviceID
	 * @param pageNO
	 * @param conQuery
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/reportExport")
	public void exportReportView(String serviceID, String style, String conQuery, HttpServletResponse response) throws Exception {
			// 报表数据源
			JRDataSource dataSourceMain = null;
			//条件的集合
			Map<String, Object> pays = null;
			if(null != conQuery && !conQuery.equals("")) {
				pays =(Map)JSON.parse(conQuery);
			}
			//{"@param_DB_NAME":"ChinaGWDatabase","@param_DT_NAME_CN":"配置县名"}
			try {
			Map<String, Object> exporterParameters = new HashMap<String, Object>();
			
			CfgExtreport reportConfigByGuid = cfgExtreportService.getReportConfigByGuid(serviceID);
			List<BaseRepdatasource> dslist = baseRepdatasourceService.getReportDataSourceByServer(serviceID);
			for (BaseRepdatasource ds : dslist) {
				if(null != ds.getDataserviceid() && null != ds.getServicetype()) {
					if(ds.getRepdatasource().equals("DefaultDataSource")) {
						List<BaseRepparmeter> dspalist = baseRepparmeterService.getReportParmByDataServer(serviceID, ds.getDataserviceid(), ds.getRepdatasource());
						String serverQuery = returnQuery(pays, dspalist);
						List dafaultdata = (List)getDataRows(ds.getServicetype(), ds.getDataserviceid(),serverQuery);
					    dataSourceMain = new JRBeanCollectionDataSource(dafaultdata);
					}else {
						List<BaseRepparmeter> sonlist = baseRepparmeterService.getReportParmByDataServer(serviceID, ds.getDataserviceid(), ds.getRepdatasource());
						String serverQuery = returnQuery(pays, sonlist);
						List datarows = (List)getDataRows(ds.getServicetype(), ds.getDataserviceid(),serverQuery);
						JRDataSource otherdata = new JRBeanCollectionDataSource(datarows);
						exporterParameters.put(ds.getRepdatasource(), otherdata);
					}
				}
			}
			List<BaseRepparmeter> parmlist = baseRepparmeterService.getReportParmByServerByType(serviceID, "templateparmeter");
			for (BaseRepparmeter parm : parmlist) {
				if((null != parm.getOptionvalue() || !"".equals(parm.getOptionvalue()))) {
					exporterParameters.put(parm.getParmetername(), parm.getOptionvalue());
				}
				for (String str : pays.keySet()) {
					if(null != parm.getAliasname() && str.equals(parm.getAliasname())) {
						exporterParameters.put(parm.getParmetername(), pays.get(str));
					}else if(null == parm.getAliasname() && str.equals(parm.getParmetername())) {
						exporterParameters.put(parm.getParmetername(), pays.get(str));
					}
				}
			}
			
			BaseReptemplate template = baseReptempletService.getReptemplateByServiceid(serviceID);
			String realpath = request.getSession().getServletContext().getRealPath(template.getTemplateUrl());
			
			if(null != style && !"".equals(style)) {
				JasperHelper.export(style, UUID.randomUUID().toString(), new File(realpath), request, response, exporterParameters, dataSourceMain);
			}
		
			
			} catch (JRException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	/*
	 *调用服务参数转换 
	 */
	public String returnQuery(Map<String, Object> pays,List<BaseRepparmeter> list) {
		Map<String, Object> map = new HashMap<String, Object>();
		for (BaseRepparmeter baseRepparmeter : list) {
			if(null != baseRepparmeter.getOptionvalue()&& !"".equals(baseRepparmeter.getOptionvalue())) {
				map.put(baseRepparmeter.getParmetername(), baseRepparmeter.getOptionvalue());
			}
			for (String str : pays.keySet()) {
				if(null != baseRepparmeter.getAliasname() && str.equals(baseRepparmeter.getAliasname())) {
					map.put(baseRepparmeter.getParmetername(), pays.get(str));
					break;
				}else if(null == baseRepparmeter.getAliasname() && str.equals(baseRepparmeter.getParmetername())) {
					map.put(baseRepparmeter.getParmetername(), pays.get(str));
					break;
				}
			}
		}
		return JSON.toJSONString(map);
	}
	/**
	 * <pre>getDataRows(根据服务ID和服务类型获取服务结果集)   
	 * @author：FanWenquan    
	 * @date：2018年1月9日 上午10:14:39   
	 * @param serviceType
	 * @param serviceID
	 * @return</pre>
	 * @throws Exception 
	 */
	private Object getDataRows(String serviceType, String serviceID, String conQuery) throws Exception {
		Object rows = null;
		switch (serviceType) {
		case "singleTableServer":
//			SingleTableServerController singleTBServer = (SingleTableServerController)BeanFactory.getBean(SingleTableServerController.class);
			// JsonDataResult singledata =
			// (JsonDataResult)singleTableServerController.querySingleTable(serviceID,
			// null, null, conQuery,""); PageResponseVo pageResponse =
			// (PageResponseVo)singledata.getData(); rows =
			// pageResponse.getRows();
			break;
		case "masterConfigServer":
//			ExtMasterController master = new ExtMasterController();
			JsonDataResult masterdata = (JsonDataResult)extMasterController.queryMasterTableList(serviceID, null, null, conQuery);
			PageResponseVo masterpageResponse =  (PageResponseVo)masterdata.getData();
			rows = masterpageResponse.getRows();
			break;
		case "treeconfigServer":
//			TreeConfigFiledController treeConfig = new TreeConfigFiledController();
			rows = treeConfigFiledController.selectTreeConfig(serviceID, null, null);
			break;
		case "executeSqlServer":
//			MultipleTableServerController multipleTB = new MultipleTableServerController();
			JsonDataResult multipledata = (JsonDataResult)multipleTableServerController.multipleTableServer(request,serviceID, null, null, conQuery, "false");
			PageResponseVo multiplepageResponse =  (PageResponseVo)multipledata.getData();
			rows = multiplepageResponse.getRows();
			break;
		}
		return rows;
	}
	
	/**
	 * <pre>queryReportQueryParams(获取报表服务的查询参数)   
	 * @author：FanWenquan    
	 * @date：2018年2月27日 上午11:55:05   
	 * @param serviceID
	 * @return</pre>
	 */
	@RequestMapping("/queryReportQueryParams")
	@ResponseBody
	public Object queryReportQueryParams(String serviceID) {
		JsonDataResult jsonResult = new JsonDataResult();
		List<Map<String,String>> result = new ArrayList<>();
		try {
			if(serviceID != null && serviceID.isEmpty() == false){
				result = cfgExtreportService.queryReportQueryParams(serviceID);
			}	
			jsonResult.setResult(0);
			jsonResult.setMessage("查询成功!");
		    jsonResult.setData(result);
		} catch (Exception e) {
			logger.error("获取报表服务的查询参数异常", e);
			jsonResult.setResult(1);
			jsonResult.setMessage("报表服务查询条件信息异常:"+e.getMessage());
		}
		return jsonResult;
	}
}
